<template>
    <div>
        <el-form label-width="85px" class="gateway-set">

            <el-form-item label="型号">
                <el-input v-model="form.gatewayModelName"
                          placeholder="请输入指令"
                          size="small"
                          disabled
                />
            </el-form-item>

            <el-form-item label="功能">
                <el-select v-model="gatewayFunction"
                           placeholder="请选择功能"
                           @change="changeGatewayFunction"
                >
                    <el-option
                        v-for="item in gatewayFunctionList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                </el-select>
            </el-form-item>

            <div v-if="this.gatewayFunction === 3">
                <el-form-item label="操作">
                    <el-button type="success" size="small" @click="restart">重启</el-button>
                </el-form-item>
            </div>

            <div v-else-if="this.gatewayFunction === 9999">

                <el-form-item label="指令">
                    <el-input v-model="commandString"
                              placeholder="请输入指令"
                              clearable
                              size="small"
                    />
                </el-form-item>

                <el-form-item label="发送">
                    <el-button type="success" size="small" @click="sendCommand">发送</el-button>
                </el-form-item>

                <el-form-item label="详情">
                    <el-input
                        :rows="8"
                        type="textarea"
                        autosize
                        placeholder=""
                        v-model="commandStringHistory"
                    >
                    </el-input>
                </el-form-item>
            </div>

            <div v-else>
                <el-form :model="setForm" ref="setForm" :rules="setFormRules" label-width="85px">

                    <el-form-item label="参数值" prop="value">
                        <el-input v-model="setForm.value" placeholder="参数值" clearable/>
                    </el-form-item>

                    <el-form-item label="操作">
                        <el-button type="success" size="small" @click="setFunc">
                            设置
                        </el-button>
                        <el-button type="success" size="small" @click="readFunc">
                            读取
                        </el-button>
                    </el-form-item>

                </el-form>
            </div>
        </el-form>
    </div>
</template>

<script>

import { sendMessage } from '@/api/netty/nettyMessage'

export default {
    name: 'index',
    props: {
        gateway: {
            type: Object
        }
    },
    data() {

        const checkIP = (rule, value, callback) => {
            const pat1 = /^((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}$/
            // const pat2 = /^((?!-)[A-Za-z0-9-]{1,63}(?<!-)\\.)+[A-Za-z]{2,6}$/
            const pat2 = /^(?=^.{3,255}$)(http(s)?:\/\/)?(www\.)?[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+(:\d+)*(\/\w+\.\w+)*([\?&]\w+=\w*)*$/
            if (value != null && value !== '') {
                if (pat1.test(value) || pat2.test(value)) {
                    callback()
                } else {
                    callback(new Error('请输入合法的ip地址'))
                }
            } else {
                callback(new Error('请输入ip地址'))
            }
        }

        return {
            sendGatewayNumber: null,
            commandString: null,
            commandStringHistory: null,
            // 表单校验
            rules: {},
            gatewayFunction: 0,
            gatewayFunctionList: [
                { 'value': 0, 'label': 'socketA' },
                { 'value': 1, 'label': 'socketB' },
                // { 'value': 2, 'label': '波特率' },
                { 'value': 3, 'label': '重启' },
                // {'value': 2, 'label': '邮件设置' },
                // {'value': 3, 'label': '解码器站号设置'},
                // {'value': 4, 'label': '通信故障次数设置' },
                { 'value': 9999, 'label': '自定义' }
            ],
            setForm: {
                value: null,
                waitTime: 10,
                loading: null
            },
            setFormRules: {
                value: [
                    { required: true, trigger: 'change', message: '请输入参数值' }
                ]
            },

            loopFault: '0',
            sensorFault: '1',
            // 原站号
            oldStationNumber: null,
            // 新站号
            newStationNumber: null,
            faultNumber: null,

            webClientId: this.genUUID(10, 16),
            messageObj: {},
            form: {}
        }
    },
    created() {
        this.form = this.gateway
    },
    destroyed() {
        if (this.ws !== undefined) {
            this.ws.close()
        }
        this.reset(this.setForm)
    },
    methods: {
        sendCommand() {
            if (this.commandStringHistory == null) {
                this.commandStringHistory = '发送：' + this.commandString + '\n'
            } else {
                this.commandStringHistory += '发送：' + this.commandString + '\n'
            }

            this.messageObj = {}

            this.messageObj.protocol = this.form.gatewayModelName
            this.messageObj.gatewayNumber = this.form.gatewayNumber
            this.messageObj.operationType = '1'
            this.messageObj.instruction = '3'
            this.messageObj.paramType = this.gatewayFunction
            this.messageObj.webClientId = this.webClientId
            this.messageObj.writeValue = this.commandString

            this.send2Web()

            this.commandString = null
        },

        send2Web() {
            sendMessage(this.messageObj).then(response => {
                if (response.code === 200) {
                    // 成功后建立websocket
                    let obj = {
                        'webClientId': this.webClientId,
                        'type': 'login'
                    }
                    this.sendMessage(obj)
                }
            }, error => {
                this.globalLoading = false
            })
        },

        getOperationName() {
            let obj = this.gatewayFunctionList.find(item => {
                return item.value === this.gatewayFunction
            })
            return obj['label']
        },

        setFunc() {
            this.$refs.setForm.validate(valid => {
                if (valid) {
                    this.messageObj = {}

                    this.wait(this.setForm)

                    this.messageObj.protocol = this.form.gatewayModelName
                    this.messageObj.gatewayNumber = this.form.gatewayNumber
                    this.messageObj.operationType = '1'
                    this.messageObj.instruction = '3'
                    this.messageObj.paramType = this.gatewayFunction
                    this.messageObj.webClientId = this.webClientId
                    this.messageObj.writeValue = this.setForm.value

                    this.send2Web()
                }
            })
        },

        readFunc() {
            this.messageObj = {}

            this.wait(this.setForm)

            this.messageObj.protocol = this.form.gatewayModelName
            this.messageObj.gatewayNumber = this.form.gatewayNumber
            this.messageObj.operationType = '0'
            this.messageObj.instruction = '3'
            this.messageObj.paramType = this.gatewayFunction
            this.messageObj.webClientId = this.webClientId

            this.send2Web()
        },

        // 重启
        restart() {

            this.messageObj = {}

            this.wait(this.setForm)

            this.messageObj.protocol = this.form.gatewayModelName
            this.messageObj.gatewayNumber = this.form.gatewayNumber
            this.messageObj.operationType = '0'
            this.messageObj.instruction = '3'
            this.messageObj.paramType = this.gatewayFunction
            this.messageObj.webClientId = this.webClientId

            this.send2Web()
        },

        // 设置解码器站号
        // setSite() {
        //     let commandArray = []
        //     commandArray.push(this.oldStationNumber)
        //     // 写命令
        //     commandArray.push(0x10)
        //     // 起始地址
        //     commandArray.push(256 >> 8 & 0xff)
        //     commandArray.push(256 & 0xff)
        //
        //     commandArray.push(0)
        //     commandArray.push(1)
        //     commandArray.push(2)
        //
        //     let controlValue = this.newStationNumber
        //
        //     commandArray.push(controlValue >> 8 & 0xff)
        //     commandArray.push(controlValue & 0xff)
        //
        //     let data = common.buildCode(commandArray)
        //     let obj = common.buildSendObject('10', 2, data, this.currentGatewayNumber, null)
        //     this.sendMessage(obj)
        // },
        wait(obj) {
            obj.loading = this.$loading({
                target: document.querySelector('.gateway-set'),
                lock: true,
                text: obj.waitTime + 's'
                // spinner: 'el-icon-loading',
                // background: 'rgba(0, 0, 0, 0.7)'
            })

            // 等待时长
            let time = obj.waitTime - 1
            obj.timer = setInterval(() => {
                if (time === 0) {
                    this.reset(obj)
                    this.$message.info('超时')
                } else {
                    obj.loading.text = time + 's'
                    --time
                }
            }, 1000)
        },
        reset(obj) {
            clearInterval(obj.timer)
            if (obj.loading !== null) {
                obj.loading.close()
            }
        },
        changeGatewayFunction(newValue) {
            this.gatewayFunction = newValue
            this.setForm.value = null
        },
        // websocket 发送消息给服务器
        sendMessage(obj) {
            if (this.ws !== undefined && this.ws.readyState === 1) {
                console.log('exist')
                // this.$websocket.sendMsg(obj)
            } else {
                this.localSocket(obj)
            }
        },
        localSocket(obj) {
            let that = this
            if ('WebSocket' in window) {
                console.log('您的浏览器支持 WebSocket')
                // console.log('that.ws', that.ws)
                if (that.ws !== undefined && that.ws.readyState === 1) {
                    console.log('exist')
                    return
                }

                that.ws = new WebSocket(that.$websocket.url)
                that.$websocket.setWs(that.ws)
                that.ws.onopen = function() {
                    console.log('开始连接')
                    // that.sendMessage(obj)
                    that.$websocket.sendMsg(obj)
                }
                // websocket 接收服务器消息
                that.ws.onmessage = function(result) {
                    console.log('收到websocket回复', result)
                    // console.log('回复data', result.data)
                    that.processData(result.data)
                }
                that.ws.onclose = function() {
                    // 防链接超时，（websocket在一定时间内没有数据交互，就会断开），关闭后重启
                    console.log('连接已关闭')
                    that.ws.close()
                    // setTimeout(() => {
                    //     that.localSocket()
                    // }, 2000)
                }
            } else {
                // 浏览器不支持 WebSocket
                console.log('您的浏览器不支持 WebSocket!')
            }
        },
        processData(json) {
            console.log('json', json)
            let data = {}
            try {
                data = JSON.parse(json)
            } catch (e) {
            }
            // console.log('data', data)
            let webClientId = data['webClientId']
            let cause = data['cause']
            if (webClientId === undefined) {
                return
            }
            // console.log('回复的webClientId', webClientId)
            let text = '操作成功'
            let value = data['value']
            let status = data['status']
            let paramType = data['paramType']
            let operationType = data['operationType']
            if (webClientId === this.webClientId) {
                // console.log('id', id)
                this.reset(this.setForm)
                if (cause !== undefined) {
                    this.$message.error(cause)
                    return
                }
                if (value !== undefined) {
                    if (operationType === '0') {
                        this.setForm.value = value
                    }
                    if (operationType === '1') {
                        this.setForm.value = null
                        if (paramType === '9999') {
                            this.commandStringHistory += '回复：' + value + '\n'
                        }
                    }
                }
                if (status !== undefined) {
                    this.form.status = status
                }
                this.$message.success(text)
            }
        }
    }
}
</script>

<style scoped>

</style>
